package com.example.demo.serviceImpl;

import com.example.demo.mapper.MenuMapper;
import com.example.demo.service.MenuService;
import com.example.demo.utils.Result;
import com.example.demo.vo.MenuVo;
import com.example.demo.vo.PageBean;
import com.example.demo.vo.userVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Override
    public int setMenu(MenuVo menuVo) {
        return menuMapper.setMenu(menuVo);
    }

    @Override
    public List<MenuVo> getMenu() {
        List<MenuVo> menuList = menuMapper.getMenubyPid(0);
        for (MenuVo menuVo : menuList){
             List<MenuVo> childrenList = menuMapper.getMenubyPid(menuVo.getId());
             if(childrenList.size() > 0){
                 childrenList = recursionMenu(childrenList);
                 menuVo.setChildren(childrenList);
             }

        }
        return menuList;
    }

    @Override
    public Result getlist(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<userVo> itemsList = menuMapper.findItem(); //查询商品
        PageInfo info=new PageInfo(itemsList);//1、PageInfo 是 pagehelper中内值的分页的信息类
        int num = (int) info.getTotal();
        PageBean<userVo> pageData = new PageBean<>(currentPage, pageSize, num);
        pageData.setRows(itemsList);
        return Result.success(pageData);
    }

    @Override
    public List<MenuVo> getAllcatalogue() {
        return menuMapper.getAllcatalogue();
    }

    @Override
    public Result del(Integer id) {
        int i = menuMapper.del(id);
        if(i == 0){
            return Result.failure(-1,"操作失败");
        }else {
            return Result.success();
        }
    }

    @Override
    public Result update(MenuVo menuVo) {
        int i = menuMapper.update(menuVo);
        if(i == 0){
            return Result.failure(-1,"操作失败");
        }else {
            return Result.success();
        }
    }


    public List<MenuVo> recursionMenu(List<MenuVo> menuList){
        for (MenuVo menuVo : menuList){
            List<MenuVo> childrenList = menuMapper.getMenubyPid(menuVo.getId());
            if(childrenList.size() > 0){
                childrenList =recursionMenu(childrenList);
                menuVo.setChildren(childrenList);
            }
        }
        return menuList;
    }
}
